import { isNil } from 'lodash';
import { FC, ReactNode } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { rootRouter } from '.';
import { AxiosCanceler } from '../service/AxiosCancel';
import { useAppSelector } from '../store';
import { searchRoute } from '../utils';
import CreateRouter from './CreateRouter';

interface Props {
    children: ReactNode;
}

export const HOME_URL = '/home';
export const LOGIN_URL = '/login';
export const NOTAUTH_URL = '/403';
export const NOTFOUND_URL = '/404';
export const NOTNETWORK_URL = '/500';

export const staticRouter = [LOGIN_URL, NOTAUTH_URL];

const axiosCancel = new AxiosCanceler();

const AuthRouter: FC<Props> = (props) => {
    const { children } = props;
    const { pathname } = useLocation();
    const route = searchRoute(pathname, rootRouter);

    const token = useAppSelector((state) => state.user.token);
    // * Dynamic Router(动态路由，根据后端返回的菜单数据生成的一维数组)
    const dynamicRouter = useAppSelector((state) => state.global.dynamicRouter);

    axiosCancel.removeAllPending();

    // 不需要进行验证页面 直接放行
    if (isNil(route.meta?.requiresAuth)) return children;

    // 进入登录页面 如果已登录跳转首页
    if (pathname === LOGIN_URL && !isNil(token)) {
        return <Navigate to={HOME_URL} replace />;
    }

    // 用户未登录跳转登录页面
    if (pathname !== LOGIN_URL && isNil(token)) {
        return <Navigate to={LOGIN_URL} replace />;
    }

    // 未获取路由跳转获取路由组件
    if (dynamicRouter.length === 0 && pathname !== LOGIN_URL) {
        return <CreateRouter />;
    }

    // Static Router(静态路由，必须配置首页地址，否则不能进首页获取菜单、按钮权限等数据)，获取数据的时候会loading，所有配置首页地址也没问题
    const routerList = dynamicRouter.concat(staticRouter);

    // *如果访问的地址没有在路由表中重定向到403页面
    if (routerList.indexOf(pathname) == -1) return <Navigate to="/403" />;

    return children;
};

export default AuthRouter;
